<script setup lang="ts">
import type { Role, RoleQueryParams } from '#/api';

import { onMounted, reactive, ref } from 'vue';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Select,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';
import { RefreshCw } from 'lucide-vue-next';

import { deleteRoleApi, getRoleListApi } from '#/api';

import AssignPermissionModal from './assign-permission-modal.vue';
import AssignRolePermissionModal from './assign-role-permission-modal.vue';
import RoleFormModal from './role-form-modal.vue';

// 查询参数
const queryParams = reactive<RoleQueryParams>({
  roleCode: undefined,
  roleName: undefined,
  status: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 弹窗
const modalVisible = ref(false);
const assignModalVisible = ref(false);
const assignRolePermissionModalVisible = ref(false);
const currentRole = ref<Role | undefined>();

// 使用 vxe-table
const [Grid, gridApi] = useVbenVxeGrid<Role>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'roleCode',
        title: '角色编码',
        minWidth: 150,
      },
      {
        field: 'roleName',
        title: '角色名称',
        minWidth: 150,
      },
      {
        field: 'description',
        title: '角色描述',
        minWidth: 200,
      },
      {
        field: 'status',
        title: '状态',
        width: 100,
        align: 'center',
        slots: { default: 'status' },
      },
      {
        field: 'createName',
        title: '创建人',
        width: 120,
      },
      {
        field: 'createTime',
        title: '创建时间',
        width: 180,
        slots: { default: 'createTime' },
      },
      {
        field: 'updateName',
        title: '更新人',
        width: 120,
      },
      {
        field: 'updateTime',
        title: '更新时间',
        width: 180,
        slots: { default: 'updateTime' },
      },
      {
        field: 'action',
        title: '操作',
        width: 380,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 查询角色列表
async function fetchRoleList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    console.log('查询角色列表 - 请求参数:', queryParams);
    const data = await getRoleListApi(queryParams);
    console.log('查询角色列表 - 响应数据:', data);

    // 处理不同的分页格式
    let list: Role[] = [];
    let total = 0;
    let current = queryParams.pageNum || 1;
    let size = queryParams.pageSize || 10;

    if (Array.isArray(data)) {
      // 后端直接返回数组（无分页信息）
      list = data;
      total = data.length;
    } else if (data.records) {
      // MyBatis Plus 分页格式：{ records, total, current, size }
      list = data.records;
      total = data.total || 0;
      current = data.current || queryParams.pageNum || 1;
      size = data.size || queryParams.pageSize || 10;
    } else if (data.list) {
      // 标准分页格式：{ list, total, pageNum, pageSize }
      list = data.list;
      total = data.total || 0;
      current = data.pageNum || queryParams.pageNum || 1;
      size = data.pageSize || queryParams.pageSize || 10;
    }

    gridApi.setState({
      gridOptions: {
        data: list,
        loading: false,
        pagerConfig: {
          total,
          currentPage: current,
          pageSize: size,
        },
      },
    });
  } catch (error: any) {
    message.error(error?.msg || '查询失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  fetchRoleList();
}

// 重置
function handleReset() {
  queryParams.roleCode = undefined;
  queryParams.roleName = undefined;
  queryParams.status = undefined;
  queryParams.pageNum = 1;
  fetchRoleList();
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  fetchRoleList();
}

// 新增
function handleAdd() {
  currentRole.value = undefined;
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: Role) {
  currentRole.value = { ...record };
  modalVisible.value = true;
}

// 分配菜单权限
function handleAssignPermission(record: Role) {
  currentRole.value = { ...record };
  assignModalVisible.value = true;
}

// 分配权限管理权限
function handleAssignRolePermission(record: Role) {
  currentRole.value = { ...record };
  assignRolePermissionModalVisible.value = true;
}

// 格式化时间
function formatDateTime(dateTime?: string) {
  if (!dateTime) return '-';
  try {
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch {
    return dateTime;
  }
}

// 删除
function handleDelete(record: Role) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除角色"${record.roleName}"吗？`,
    onOk: async () => {
      try {
        await deleteRoleApi(record.id!);
        message.success('删除成功');
        fetchRoleList();
      } catch (error: any) {
        // 错误消息由响应拦截器统一处理，这里不需要再显示
        console.error('删除角色失败:', error);
      }
    },
  });
}

// 刷新
function handleRefresh() {
  fetchRoleList();
  message.success('刷新成功');
}

onMounted(() => {
  fetchRoleList();
});
</script>

<template>
  <div class="flex h-full flex-col p-4">
    <!-- 搜索表单 -->
    <Card :bordered="false" class="mb-4 flex-shrink-0">
      <Form layout="inline" :model="queryParams">
        <FormItem label="角色编码">
          <Input
            v-model:value="queryParams.roleCode"
            placeholder="请输入角色编码"
            allow-clear
            @press-enter="handleQuery"
          />
        </FormItem>
        <FormItem label="角色名称">
          <Input
            v-model:value="queryParams.roleName"
            placeholder="请输入角色名称"
            allow-clear
            @press-enter="handleQuery"
          />
        </FormItem>
        <FormItem label="状态">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 180px"
          >
            <Select.Option :value="1">启用</Select.Option>
            <Select.Option :value="0">禁用</Select.Option>
          </Select>
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleQuery">查询</Button>
            <Button @click="handleReset">重置</Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 表格 -->
    <Card :bordered="false" class="flex flex-1 flex-col overflow-hidden">
      <div class="mb-4 flex flex-shrink-0 justify-between">
        <Button v-permission="'sys:role:add'" type="primary" @click="handleAdd">
          新增角色
        </Button>
        <Tooltip title="刷新">
          <Button @click="handleRefresh">
            <RefreshCw :size="16" />
          </Button>
        </Tooltip>
      </div>

      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 状态列 -->
          <template #status="{ row }">
            <Tag v-if="row.status === 1" color="success">启用</Tag>
            <Tag v-else color="error">禁用</Tag>
          </template>

          <!-- 创建时间列 -->
          <template #createTime="{ row }">
            <span class="text-xs text-gray-600">{{ formatDateTime(row.createTime) }}</span>
          </template>

          <!-- 更新时间列 -->
          <template #updateTime="{ row }">
            <span class="text-xs text-gray-600">{{ formatDateTime(row.updateTime) }}</span>
          </template>

          <!-- 操作列 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'sys:role:edit'"
                type="link"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </Button>
              <Button
                v-permission="'sys:role:assignMenuPerm'"
                type="link"
                size="small"
                @click="handleAssignPermission(row)"
              >
                分配菜单权限
              </Button>
              <Button
                v-permission="'sys:role:assignPerm'"
                type="link"
                size="small"
                @click="handleAssignRolePermission(row)"
              >
                分配权限
              </Button>
              <Button
                v-permission="'sys:role:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <RoleFormModal
      v-model:open="modalVisible"
      :role-data="currentRole"
      @success="handleQuery"
    />

    <!-- 分配菜单权限弹窗 -->
    <AssignPermissionModal
      v-model:open="assignModalVisible"
      :role-data="currentRole"
      @success="handleQuery"
    />

    <!-- 分配权限管理权限弹窗 -->
    <AssignRolePermissionModal
      v-model:open="assignRolePermissionModalVisible"
      :role-data="currentRole"
      @success="handleQuery"
    />
  </div>
</template>
